import { createStore } from 'vuex'
import * as projectApi from '../api/project'
import * as taskApi from '../api/task'
import * as fileApi from '../api/file'
import api from '../api' // 导入自定义的api实例
import axios from 'axios'
import { normalizeApiResponse } from '../utils/helpers'

export default createStore({
  state: {
    user: null,
    projects: [],
    currentProject: null,
    tasks: [],
    currentTask: null,
    subtasks: [],
    atomicTasks: [],
    blockedTasks: [],
    taskDependencies: {},
    taskProgressHistory: [],
    taskExecutions: [],
    fileHistory: {},
    aiConversations: [],
    notifications: [],
    loading: {
      projects: false,
      tasks: false,
      taskDetail: false,
      atomicTasks: false,
      updateProject: false
    },
    error: null,
    projectTasks: [],
    projectMembers: [],
    users: []
  },
  getters: {
    isAuthenticated(state) {
      return !!state.user
    },
    currentProject(state) {
      return state.currentProject
    },
    currentTask(state) {
      return state.currentTask
    },
    getSubtasks(state) {
      return state.subtasks
    },
    getAtomicTasks(state) {
      return state.atomicTasks
    },
    getBlockedTasks(state) {
      return state.blockedTasks
    },
    getTaskDependencies(state) {
      return state.taskDependencies
    },
    getProgressHistory(state) {
      return state.taskProgressHistory
    },
    getFileHistory(state) {
      return state.fileHistory
    },
    getAIConversations(state) {
      return state.aiConversations
    },
    getNotifications(state) {
      return state.notifications
    },
    isLoading: (state) => (key) => {
      return state.loading[key] || false
    }
  },
  mutations: {
    setUser(state, user) {
      state.user = user
    },
    setTenant(state, tenant) {
      state.tenant = tenant
    },
    setAvailableTenants(state, tenants) {
      state.availableTenants = tenants
    },
    setProjects(state, projects) {
      state.projects = projects
    },
    setCurrentProject(state, project) {
      state.currentProject = project
    },
    setTasks(state, tasks) {
      state.tasks = tasks
    },
    setCurrentTask(state, task) {
      state.currentTask = task
    },
    setSubtasks(state, subtasks) {
      state.subtasks = subtasks
    },
    setAtomicTasks(state, tasks) {
      state.atomicTasks = tasks
    },
    setBlockedTasks(state, tasks) {
      state.blockedTasks = tasks
    },
    setTaskDependencies(state, dependencies) {
      state.taskDependencies = dependencies
    },
    setProgressHistory(state, history) {
      state.taskProgressHistory = history
    },
    setFileHistory(state, history) {
      state.fileHistory = history
    },
    setAIConversations(state, conversations) {
      state.aiConversations = conversations
    },
    setNotifications(state, notifications) {
      state.notifications = notifications
    },
    setLoading(state, { key, status }) {
      state.loading[key] = status
    },
    setError(state, error) {
      state.error = error
    },
    clearError(state) {
      state.error = null
    },
    addProject(state, project) {
      state.projects.unshift(project)
    },
    addTask(state, task) {
      state.tasks.unshift(task)
    },
    SET_PROJECTS(state, projects) {
      state.projects = projects;
    },
    SET_CURRENT_PROJECT(state, project) {
      state.currentProject = project;
    },
    SET_PROJECT_TASKS(state, tasks) {
      state.projectTasks = tasks;
    },
    SET_PROJECT_MEMBERS(state, members) {
      state.projectMembers = members;
    },
    SET_USERS(state, users) {
      state.users = users;
    },
    ADD_PROJECT_MEMBER(state, member) {
      state.projectMembers.push(member);
    },
    REMOVE_PROJECT_MEMBER(state, memberId) {
      state.projectMembers = state.projectMembers.filter(m => m.id !== memberId);
    },
    UPDATE_PROJECT_OWNER(state, newOwnerId) {
      if (state.currentProject) {
        state.currentProject.owner_id = newOwnerId;
        
        // 更新成员列表中的owner状态
        state.projectMembers.forEach(member => {
          member.is_owner = member.id === newOwnerId;
        });
      }
    },
    setCurrentUser(state, user) {
      state.auth.user = user
    },
    setTaskDetail(state, task) {
      state.currentTask = task
    },
    setProjectTasks(state, tasks) {
      state.projectTasks = tasks
    },
    setProjectMembers(state, members) {
      state.projectMembers = members
    },
    setUsers(state, users) {
      state.users = users
    },
    removeProjectMember(state, memberId) {
      state.projectMembers = state.projectMembers.filter(m => m.id !== memberId)
    },
    updateProjectOwner(state, newOwnerId) {
      if (state.currentProject) {
        state.currentProject.owner_id = newOwnerId
        
        // 更新成员列表中的owner状态
        state.projectMembers.forEach(member => {
          member.is_owner = member.id === newOwnerId
        })
      }
    }
  },
  actions: {
    // 登录
    async login({ commit }, credentials) {
      commit('setLoading', { key: 'auth', status: true })
      try {
        console.log('尝试登录，发送数据:', credentials)
        const response = await api.post('/auth/login', credentials)
        console.log('登录API响应:', response)
        
        if (response.data && response.data.status === 'success') {
          const userData = response.data.data
          if (userData && userData.token) {
            // 清除旧token（如果有）
            localStorage.removeItem('token')
            
            // 存储新token
            console.log('保存token到本地存储')
            localStorage.setItem('token', userData.token)
            
            // 验证token是否正确保存
            const savedToken = localStorage.getItem('token')
            console.log('验证保存的token:', savedToken ? '保存成功' : '保存失败')
            
            commit('setUser', userData.user)
            commit('setTenant', { code: credentials.tenant_code })
            
            // 标记已登录
            console.log('登录成功')
            return true
          } else {
            commit('setError', '登录成功但未收到有效token')
            console.error('登录响应中缺少token:', userData)
            return false
          }
        } else {
          commit('setError', response.data?.message || '登录失败')
          console.error('登录API返回错误:', response.data)
          return false
        }
      } catch (error) {
        console.error('登录请求异常:', error)
        commit('setError', error.response?.data?.message || '登录请求失败')
        throw error
      } finally {
        commit('setLoading', { key: 'auth', status: false })
      }
    },
    
    // 注册
    async register({ commit }, userData) {
      commit('setLoading', { key: 'register', status: true })
      commit('clearError')
      try {
        const response = await api.post('/auth/register', userData)
        const { user, tenant, token } = response.data
        
        // 保存token到localStorage
        localStorage.setItem('token', token)
        // 设置axios默认header
        api.defaults.headers.common['Authorization'] = `Bearer ${token}`
        
        commit('setUser', user)
        commit('setTenant', tenant)
        return { user, tenant }
      } catch (error) {
        commit('setError', error.response?.data?.message || '注册失败')
        throw error
      } finally {
        commit('setLoading', { key: 'register', status: false })
      }
    },
    
    // 登出
    logout({ commit }) {
      localStorage.removeItem('token')
      delete api.defaults.headers.common['Authorization']
      commit('setUser', null)
      commit('setTenant', null)
    },
    
    // 获取当前用户信息
    async fetchCurrentUser({ commit }) {
      commit('setLoading', { key: 'user', status: true })
      try {
        const response = await api.get('/auth/me')
        const { user, tenant } = response.data
        commit('setUser', user)
        commit('setTenant', tenant)
        return { user, tenant }
      } catch (error) {
        if (error.response && error.response.status === 401) {
          // 如果未授权，清除本地存储的token
          localStorage.removeItem('token')
        }
        commit('setError', error.response?.data?.message || '获取用户信息失败')
        throw error
      } finally {
        commit('setLoading', { key: 'user', status: false })
      }
    },
    
    // 获取可用租户列表
    async fetchAvailableTenants({ commit }) {
      commit('setLoading', { key: 'tenants', status: true })
      try {
        const response = await api.get('/auth/tenants')
        // 检查响应格式并正确处理
        if (response.data && response.data.status === 'success') {
          commit('setAvailableTenants', response.data.data || [])
          return response.data.data || []
        } else {
          commit('setAvailableTenants', [])
          return []
        }
      } catch (error) {
        commit('setError', error.response?.data?.message || '获取租户列表失败')
        throw error
      } finally {
        commit('setLoading', { key: 'tenants', status: false })
      }
    },
    
    // 创建新租户
    async createTenant({ commit }, tenantData) {
      commit('setLoading', { key: 'createTenant', status: true })
      try {
        const response = await api.post('/auth/tenants', tenantData)
        return response.data
      } catch (error) {
        commit('setError', error.response?.data?.message || '创建租户失败')
        throw error
      } finally {
        commit('setLoading', { key: 'createTenant', status: false })
      }
    },
    
    // 获取项目列表
    async fetchProjects({ commit, dispatch }) {
      commit('setLoading', { key: 'projects', status: true })
      try {
        console.log('开始获取项目列表')
        const response = await api.get('/projects')
        console.log('项目列表API响应:', response)
        
        // 使用工具函数处理API响应，确保得到数组
        const projects = normalizeApiResponse(response, 'array')
        console.log('处理后的项目列表数据:', projects)
        
        // 设置项目列表
        commit('setProjects', projects)
        return projects
      } catch (error) {
        console.error('获取项目列表失败:', error)
        commit('setError', error.response?.data?.message || '获取项目列表失败')
        commit('setProjects', [])
        throw error
      } finally {
        commit('setLoading', { key: 'projects', status: false })
      }
    },
    
    // 创建新项目
    async createProject({ commit, dispatch }, projectData) {
      commit('setLoading', { key: 'createProject', status: true })
      try {
        const response = await api.post('/projects', projectData)
        console.log('创建项目响应:', response)
        
        // 不论响应格式如何，都重新获取项目列表
        await dispatch('fetchProjects')
        
        // 根据不同的响应格式返回数据
        if (response.data && response.data.status === 'success') {
          return response.data.data
        } else {
          return response.data
        }
      } catch (error) {
        console.error('创建项目失败:', error)
        commit('setError', error.response?.data?.message || '创建项目失败')
        throw error
      } finally {
        commit('setLoading', { key: 'createProject', status: false })
      }
    },
    
    // 获取项目详情
    async fetchProjectDetail({ commit }, projectId) {
      commit('setLoading', { key: 'projectDetail', status: true })
      try {
        console.log('开始获取项目详情:', projectId)
        const response = await api.get(`/projects/${projectId}`)
        console.log('项目详情API响应:', response)
        
        // 使用工具函数处理API响应，确保得到对象
        const project = normalizeApiResponse(response, 'object')
        console.log('处理后的项目详情数据:', project)
        
        if (project && Object.keys(project).length > 0) {
          commit('setCurrentProject', project)
          return project
        } else {
          console.warn('项目详情为空')
          commit('setCurrentProject', null)
          return null
        }
      } catch (error) {
        console.error('获取项目详情失败:', error)
        commit('setError', error.response?.data?.message || '获取项目详情失败')
        commit('setCurrentProject', null)
        throw error
      } finally {
        commit('setLoading', { key: 'projectDetail', status: false })
      }
    },
    
    // 获取项目任务列表
    async fetchProjectTasks({ commit, dispatch }, projectId) {
      commit('setLoading', { key: 'tasks', status: true })
      try {
        const response = await projectApi.getProjectTasks(projectId)
        console.log('项目任务列表响应:', response)
        
        // 使用工具函数处理API响应
        const tasks = normalizeApiResponse(response, 'array')
        console.log('处理后的任务数据:', tasks)
        
        // 同时设置tasks和projectTasks，确保两个地方都能访问到
        commit('setTasks', tasks)
        commit('setProjectTasks', tasks)
        return tasks
      } catch (error) {
        console.error('获取任务列表失败:', error)
        commit('setTasks', [])
        commit('setProjectTasks', [])
        throw error
      } finally {
        commit('setLoading', { key: 'tasks', status: false })
      }
    },
    
    // 创建项目任务
    async createProjectTask({ commit, dispatch }, { projectId, taskData }) {
      commit('setLoading', { key: 'createTask', status: true })
      try {
        const response = await projectApi.createProjectTask(projectId, taskData)
        
        // 创建成功后重新获取任务列表
        await dispatch('fetchProjectTasks', projectId)
        
        return response.data
      } catch (error) {
        console.error('创建任务失败:', error)
        throw error
      } finally {
        commit('setLoading', { key: 'createTask', status: false })
      }
    },
    
    // 删除项目任务
    async deleteProjectTask({ commit, dispatch }, { projectId, taskId }) {
      commit('setLoading', { key: 'deleteTask', status: true })
      try {
        const response = await projectApi.deleteProjectTask(projectId, taskId)
        
        // 删除成功后重新获取任务列表
        await dispatch('fetchProjectTasks', projectId)
        
        return response.data
      } catch (error) {
        console.error('删除任务失败:', error)
        throw error
      } finally {
        commit('setLoading', { key: 'deleteTask', status: false })
      }
    },
    
    // 获取任务详情
    async fetchTaskDetail({ commit }, taskId) {
      commit('setLoading', { key: 'taskDetail', status: true })
      try {
        console.log('开始从API获取任务详情:', taskId)
        const response = await taskApi.getTaskDetail(taskId)
        console.log('原始API响应:', response)
        
        // 检查response是否包含data字段
        if (response.data) {
          console.log('响应数据结构:', response.data)
          
          // 如果response.data已经包含status字段，说明是直接返回的API响应
          if (response.data.status === 'success' && response.data.data) {
            const taskDetail = response.data.data
            console.log('任务详情数据:', taskDetail)
            console.log('拆分版本数据:', taskDetail.breakdown_version)
            
            // 设置当前任务
            commit('setCurrentTask', taskDetail)
            
            // 设置子任务
            if (taskDetail.subtasks && Array.isArray(taskDetail.subtasks)) {
              console.log('子任务数据:', taskDetail.subtasks)
              commit('setSubtasks', taskDetail.subtasks)
            } else {
              console.log('无子任务数据或数据不是数组')
              commit('setSubtasks', [])
            }
            
            return taskDetail
          }
          // 如果response.data本身就是任务详情对象
          else if (typeof response.data === 'object' && response.data.id) {
            const taskDetail = response.data
            console.log('任务详情数据(直接):', taskDetail)
            
            // 设置当前任务
            commit('setCurrentTask', taskDetail)
            
            // 设置子任务
            if (taskDetail.subtasks && Array.isArray(taskDetail.subtasks)) {
              console.log('子任务数据:', taskDetail.subtasks)
              commit('setSubtasks', taskDetail.subtasks)
            } else {
              console.log('无子任务数据或数据不是数组')
              commit('setSubtasks', [])
            }
            
            return taskDetail
          }
          else {
            console.error('API响应格式无法识别:', response)
            commit('setError', '任务详情数据格式错误')
            return null
          }
        } else {
          console.error('API响应不包含data字段:', response)
          commit('setError', '任务详情数据格式错误')
          return null
        }
      } catch (error) {
        console.error('获取任务详情失败:', error)
        commit('setError', error.message || '获取任务详情失败')
        throw error
      } finally {
        commit('setLoading', { key: 'taskDetail', status: false })
      }
    },
    
    // 更新项目信息
    async updateProject({ commit }, { projectId, projectData }) {
      commit('setLoading', { key: 'updateProject', status: true })
      try {
        console.log('开始更新项目:', projectId)
        console.log('更新项目数据详情:', JSON.stringify(projectData, null, 2))
        
        // 检查请求数据中的特殊字段
        if(projectData.project_folder_path) {
          console.log('项目文件夹路径:', projectData.project_folder_path)
        }
        if(projectData.db_host) {
          console.log('数据库连接信息:', {
            db_type: projectData.db_type,
            db_host: projectData.db_host,
            db_port: projectData.db_port,
            db_name: projectData.db_name,
            db_username: projectData.db_username
          })
        }
        
        const response = await api.put(`/projects/${projectId}`, projectData)
        console.log('更新项目响应状态:', response.status)
        console.log('更新项目响应数据:', JSON.stringify(response.data, null, 2))
        
        // 使用工具函数处理API响应
        const updatedProject = normalizeApiResponse(response, 'object')
        
        if (updatedProject) {
          console.log('项目更新成功，更新后的数据:', JSON.stringify(updatedProject, null, 2))
          commit('setCurrentProject', updatedProject)
          return updatedProject
        }
        console.log('项目更新失败: API响应处理后没有返回有效数据')
        return null
      } catch (error) {
        console.error('更新项目失败:', error)
        
        // 处理不同类型的错误
        if (error.response) {
          const { status, data } = error.response
          
          // 处理特定状态码
          if (status === 403) {
            const errorMessage = data?.message || '您没有权限编辑此项目。只有项目负责人或创建者可以编辑项目信息。'
            commit('setError', errorMessage)
            throw new Error(errorMessage)
          } else if (status === 401) {
            const errorMessage = '会话已过期，请重新登录'
            commit('setError', errorMessage)
            throw new Error(errorMessage)
          } else if (status === 404) {
            const errorMessage = '项目不存在或已被删除'
            commit('setError', errorMessage)
            throw new Error(errorMessage)
          } else {
            // 其他错误
            const errorMessage = data?.message || `更新项目失败 (${status})`
            commit('setError', errorMessage)
            throw new Error(errorMessage)
          }
        } else {
          // 网络错误或其他错误
          commit('setError', error.message || '网络错误，无法连接到服务器')
          throw error
        }
      } finally {
        commit('setLoading', { key: 'updateProject', status: false })
      }
    },
    
    // 手动拆分任务
    async manualBreakdownTask({ commit, dispatch }, { taskId, tasksData }) {
      commit('setLoading', { key: 'taskBreakdown', status: true })
      try {
        const response = await taskApi.manualBreakdownTask(taskId, tasksData)
        if (response.data && response.data.status === 'success') {
          // 重新获取任务详情以更新状态
          await dispatch('fetchTaskDetail', taskId)
          return response.data.data
        }
        return null
      } catch (error) {
        console.error('手动拆分任务失败:', error)
        throw error
      } finally {
        commit('setLoading', { key: 'taskBreakdown', status: false })
      }
    },
    
    // 获取任务拆分版本列表
    async fetchTaskBreakdownVersions({ commit }, taskId) {
      commit('setLoading', { key: 'breakdownVersions', status: true })
      try {
        const response = await taskApi.getTaskBreakdownVersions(taskId)
        if (response.data && response.data.status === 'success') {
          return response.data.data
        }
        return []
      } catch (error) {
        console.error('获取任务拆分版本列表失败:', error)
        throw error
      } finally {
        commit('setLoading', { key: 'breakdownVersions', status: false })
      }
    },
    
    // 获取拆分版本详情
    async fetchBreakdownVersionDetail({ commit }, versionId) {
      commit('setLoading', { key: 'versionDetail', status: true })
      try {
        const response = await taskApi.getBreakdownVersionDetail(versionId)
        if (response.data && response.data.status === 'success') {
          return response.data.data
        }
        return null
      } catch (error) {
        console.error('获取拆分版本详情失败:', error)
        throw error
      } finally {
        commit('setLoading', { key: 'versionDetail', status: false })
      }
    },
    
    // 更新任务拆分版本状态
    async updateBreakdownVersionStatus({ commit, dispatch }, { versionId, status, taskId }) {
      try {
        const response = await taskApi.updateBreakdownVersionStatus(versionId, status)
        if (response.data && response.data.status === 'success') {
          // 如果提供了taskId，则重新获取任务详情
          if (taskId) {
            await dispatch('fetchTaskDetail', taskId)
          }
          return response.data.data
        }
        return null
      } catch (error) {
        console.error('更新任务拆分版本状态失败:', error)
        throw error
      }
    },
    
    // 更新子任务
    async updateSubtask({ commit, dispatch }, { subtaskId, updateData }) {
      try {
        const response = await taskApi.updateSubtask(subtaskId, updateData)
        if (response.data.status === 'success') {
          // 更新成功后重新获取任务详情
          return response.data
        } else {
          throw new Error(response.data.message || '更新子任务失败')
        }
      } catch (error) {
        console.error('更新子任务失败:', error)
        throw error
      }
    },
    
    // 执行任务
    async executeTask({ commit }, { subtaskId, executor, result }) {
      try {
        const response = await taskApi.executeTask(subtaskId, executor, result)
        if (response.data && response.data.status === 'success') {
          return response.data.data
        }
        return null
      } catch (error) {
        console.error('执行任务失败:', error)
        throw error
      }
    },
    
    // 获取可执行的原子任务列表
    async fetchAtomicTasks({ commit }) {
      commit('setLoading', { key: 'atomicTasks', status: true })
      try {
        console.log('开始获取原子任务列表')
        const response = await taskApi.getAtomicTasks()
        console.log('原子任务API响应:', response)
        
        // 处理API响应数据
        if (response.data && response.data.status === 'success') {
          const tasks = response.data.data || []
          console.log('获取到的原子任务:', tasks)
          commit('setAtomicTasks', tasks)
          return tasks
        } else {
          console.warn('原子任务API返回了非标准格式:', response)
          commit('setAtomicTasks', [])
          return []
        }
      } catch (error) {
        console.error('获取原子任务列表失败:', error)
        commit('setError', error.message || '获取原子任务列表失败')
        
        // 提供模拟数据以便前端可以正常显示
        const mockTasks = [
          {
            id: 1,
            title: '示例原子任务1',
            description: '这是一个示例原子任务',
            status: 'pending',
            project_id: 1,
            project_name: '示例项目',
            main_task_id: 1,
            main_task_title: '示例主任务'
          }
        ]
        commit('setAtomicTasks', mockTasks)
        return mockTasks
      } finally {
        commit('setLoading', { key: 'atomicTasks', status: false })
      }
    },
    
    // 获取原子任务详情
    async fetchAtomicTaskDetail({ commit }, atomicTaskId) {
      commit('setLoading', { key: 'atomicTaskDetail', status: true })
      try {
        console.log('开始获取原子任务详情:', atomicTaskId)
        const response = await taskApi.getAtomicTaskDetail(atomicTaskId)
        console.log('原子任务详情API响应:', response)
        
        // 处理API响应数据
        if (response.data && response.data.status === 'success') {
          const taskDetail = response.data.data || {}
          console.log('获取到的原子任务详情:', taskDetail)
          return taskDetail
        } else {
          console.warn('原子任务详情API返回了非标准格式:', response)
          return null
        }
      } catch (error) {
        console.error('获取原子任务详情失败:', error)
        commit('setError', error.message || '获取原子任务详情失败')
        
        // 提供模拟数据以便前端可以正常显示
        const mockData = {
          task: {
            id: atomicTaskId,
            title: '示例原子任务',
            description: '这是一个示例原子任务描述',
            status: 'pending',
            project_id: 1,
            project_name: '示例项目',
            main_task_id: 1,
            main_task_title: '示例主任务',
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            is_atomic: true,
            is_executed: false,
            execution_count: 0,
            last_executed_at: null,
            execution_mode: 'ai'
          },
          executions: [],
          dependencies: []
        }
        return mockData
      } finally {
        commit('setLoading', { key: 'atomicTaskDetail', status: false })
      }
    },
    
    // 获取阻塞的任务列表
    async fetchBlockedTasks({ commit }) {
      try {
        const response = await taskApi.getBlockedTasks()
        commit('setBlockedTasks', response.data)
      } catch (error) {
        commit('setError', error.message)
      }
    },
    
    // 提交任务执行结果
    async submitExecutionResult({ commit }, { executionId, result }) {
      try {
        const response = await taskApi.submitExecutionResult(executionId, result)
        return response
      } catch (error) {
        commit('setError', error.message)
        throw error
      }
    },
    
    // 审核任务执行
    async reviewExecution({ commit }, { executionId, reviewData }) {
      try {
        const response = await taskApi.reviewExecution(executionId, reviewData)
        return response
      } catch (error) {
        commit('setError', error.message)
        throw error
      }
    },
    
    // 回退任务执行
    async rollbackExecution({ commit }, { executionId, reason }) {
      try {
        const response = await taskApi.rollbackExecution(executionId, reason)
        return response
      } catch (error) {
        commit('setError', error.message)
        throw error
      }
    },
    
    // 获取任务依赖关系
    async fetchTaskDependencies({ commit }, taskId) {
      try {
        const response = await taskApi.getTaskDependencies(taskId)
        commit('setTaskDependencies', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message)
      }
    },
    
    // 添加任务依赖关系
    async addTaskDependency({ commit, dispatch }, { dependentTaskId, dependencyData }) {
      try {
        const response = await taskApi.addTaskDependency(dependentTaskId, dependencyData)
        // 重新获取依赖关系
        dispatch('fetchTaskDependencies', dependentTaskId)
        return response
      } catch (error) {
        commit('setError', error.message)
        throw error
      }
    },
    
    // 移除任务依赖关系
    async removeTaskDependency({ commit, dispatch }, { dependencyId, taskId }) {
      try {
        const response = await taskApi.removeTaskDependency(dependencyId)
        // 重新获取依赖关系
        if (taskId) {
          dispatch('fetchTaskDependencies', taskId)
        }
        return response
      } catch (error) {
        commit('setError', error.message)
        throw error
      }
    },
    
    // 更新任务进度
    async updateTaskProgress({ commit }, { taskId, progressData }) {
      try {
        const response = await taskApi.updateTaskProgress(taskId, progressData)
        return response
      } catch (error) {
        commit('setError', error.message)
        throw error
      }
    },
    
    // 获取任务进度历史
    async fetchTaskProgressHistory({ commit }, taskId) {
      try {
        const response = await taskApi.getTaskProgressHistory(taskId)
        commit('setProgressHistory', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message)
      }
    },
    
    // 获取文件变更历史
    async fetchFileHistory({ commit }, filePath) {
      try {
        const response = await fileApi.getFileHistory(filePath)
        commit('setFileHistory', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message)
      }
    },
    
    // 获取任务的AI会话记录
    async fetchTaskAIConversations({ commit }, taskId) {
      try {
        const response = await taskApi.getTaskAIConversations(taskId)
        commit('setAIConversations', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message)
      }
    },
    
    // 获取任务的通知
    async fetchTaskNotifications({ commit }, taskId) {
      try {
        const response = await taskApi.getTaskNotifications(taskId)
        commit('setNotifications', response.data)
        return response.data
      } catch (error) {
        commit('setError', error.message)
      }
    },
    
    // 添加子任务
    async addSubtask({ commit, dispatch }, subtaskData) {
      try {
        const breakdown_version_id = subtaskData.breakdown_version_id;
        if (!breakdown_version_id) {
          throw new Error('缺少拆分版本ID (breakdown_version_id)');
        }
        
        // 保存 main_task_id 用于后续刷新数据
        const main_task_id = subtaskData.main_task_id;
        
        const response = await taskApi.addSubtaskByVersion(breakdown_version_id, subtaskData);
        
        if (response.data && response.data.status === 'success') {
          // 如果任务添加成功，直接重新获取主任务
          if (main_task_id) {
            await dispatch('fetchTaskDetail', main_task_id);
          }
          
          return response.data.data;
        }
        return null;
      } catch (error) {
        console.error('添加子任务失败:', error);
        throw error;
      }
    },
    
    // 删除子任务
    async deleteSubtask({ commit, dispatch }, { subtaskId, projectId }) {
      try {
        const response = await taskApi.deleteSubtask(subtaskId);
        if (response.data && response.data.status === 'success') {
          // 删除成功后重新获取项目任务列表
          if (projectId) {
            await dispatch('fetchProjectTasks', projectId);
          }
          return response.data;
        }
        return null;
      } catch (error) {
        console.error('删除子任务失败:', error);
        
        // 即使API返回错误，也尝试重新获取数据，因为删除操作可能已部分成功
        try {
          if (projectId) {
            await dispatch('fetchProjectTasks', projectId);
          }
        } catch (refreshError) {
          console.error('刷新数据失败:', refreshError);
        }
        
        // 仍然抛出原始错误，让调用者决定如何处理
        throw error;
      }
    },
    
    // 获取项目成员列表
    async fetchProjectMembers({ commit, dispatch }, projectId) {
      commit('setLoading', { key: 'projectMembers', status: true })
      try {
        const response = await api.get(`/projects/${projectId}/members`)
        if (response.data && response.data.status === 'success') {
          commit('setProjectMembers', response.data.data || [])
        } else {
          throw new Error(response.data.message || '获取项目成员列表失败')
        }
      } catch (error) {
        console.error('获取项目成员列表错误:', error)
        throw error
      } finally {
        commit('setLoading', { key: 'projectMembers', status: false })
      }
    },
    
    // 获取所有用户
    async fetchUsers({ commit, dispatch }) {
      commit('setLoading', { key: 'users', status: true })
      try {
        console.log('开始获取用户列表...')
        // 使用租户ID筛选，只获取当前租户下的用户
        const response = await api.get('/users?tenant_only=true')
        console.log('用户列表API响应:', response)
        
        let users = []
        if (response.data && response.data.status === 'success') {
          users = Array.isArray(response.data.data) ? response.data.data : []
          console.log(`获取到 ${users.length} 个用户`)
          commit('setUsers', users)
        } else {
          console.warn('获取用户列表API返回的数据格式异常:', response.data)
          commit('setUsers', [])
          throw new Error(response.data?.message || '获取用户列表失败')
        }
        return users
      } catch (error) {
        console.error('获取用户列表错误:', error)
        commit('setUsers', [])
        throw error
      } finally {
        commit('setLoading', { key: 'users', status: false })
      }
    },
    
    // 添加项目成员
    async addProjectMember({ commit, dispatch }, { projectId, memberData }) {
      try {
        console.log(`开始添加项目成员到项目 ${projectId}，成员数据:`, memberData)
        
        // 确保数据格式正确
        if (!memberData.user_id || !memberData.role) {
          throw new Error('缺少必要的成员信息 (user_id 或 role)')
        }
        
        const response = await api.post(`/projects/${projectId}/members`, memberData)
        console.log('添加项目成员API响应:', response)
        
        if (response.data && response.data.status === 'success') {
          console.log('成员添加成功，刷新成员列表')
          // 重新获取成员列表
          await dispatch('fetchProjectMembers', projectId)
          return response.data.data
        } else {
          const errorMsg = response.data?.message || '添加项目成员失败'
          console.error('添加项目成员失败:', errorMsg)
          throw new Error(errorMsg)
        }
      } catch (error) {
        console.error('添加项目成员错误:', error)
        throw error
      }
    },
    
    // 移除项目成员
    async removeProjectMember({ commit, dispatch }, { projectId, memberId }) {
      try {
        const response = await api.delete(`/projects/${projectId}/members/${memberId}`)
        if (response.data.status === 'success') {
          commit('REMOVE_PROJECT_MEMBER', memberId)
          return true
        } else {
          throw new Error(response.data.message || '移除项目成员失败')
        }
      } catch (error) {
        console.error('移除项目成员错误:', error)
        throw error
      }
    },
    
    // 设置项目负责人
    async setProjectOwner({ commit, dispatch }, { projectId, memberId }) {
      try {
        const response = await api.put(`/projects/${projectId}`, { owner_id: memberId })
        if (response.data.status === 'success') {
          commit('UPDATE_PROJECT_OWNER', memberId)
          // 重新获取项目信息和成员列表
          await dispatch('fetchProjectDetail', projectId)
          await dispatch('fetchProjectMembers', projectId)
          return true
        } else {
          throw new Error(response.data.message || '设置项目负责人失败')
        }
      } catch (error) {
        console.error('设置项目负责人错误:', error)
        throw error
      }
    }
  }
}) 